package org.laizili.solution.leetcode;

/**
 * <a href="https://leetcode-cn.com/problems/max-consecutive-ones-iii/">1004-最大连续1的个数 III</a>
 * <p>
 * tags: 双指针; 滑动窗口
 * </p>
 */
public class Problem1004 {
    private static class Solution {
        public int longestOnes(int[] nums, int k) {
            // 双指针（滑动窗口）
            int left = 0, right = 0;
            int res = Integer.MIN_VALUE;
            int curAns = 0;
            while (right < nums.length) {
                if (k > 0) {
                    if (nums[right] == 0) {
                        k--;
                    }
                    curAns++;
                    right++;
                } else {
                    if (nums[right] == 0) { // k == 0 && nums[right] == 0
                        if (res < curAns) {
                            res = curAns;
                        }
                        if (nums[left++] == 0) {
                            k++;
                        }
                        curAns--;
                    } else {
                        curAns++;
                        right++;
                    }
                }
            }
            return Math.max(res, curAns);
        }
    }
}
